package com.corpgovernment.organization.service;

import java.util.List;

import com.corpgovernment.organization.event.OrgInitEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import com.corpgovernment.api.organization.model.org.OrgConfigInfoVo;
import com.corpgovernment.api.organization.model.org.request.SaveOrgConfigRequest;
import com.corpgovernment.organization.dataloader.db.MbOrgInfoLoader;
import com.corpgovernment.organization.entity.db.MbOrgInfo;
import com.corpgovernment.organization.event.OrgInitEvent;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.JsonUtils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zl.cui
 * @date 2023/8/22
 */
@Service
@Slf4j
public class ImportOrganizationConfigService {
    @Autowired
    private IOrgConfigService orgConfigService;
    @Autowired
    private MbOrgInfoLoader mbOrgInfoLoader;


    private static final String TRUE = "是";
    private static final String FALSE = "否";
    private static final String T = "T";
    private static final String F = "F";
    /**
     * 开票方式：企服开票/企业开票
     */
    private static final String INVOICE_WAY = "企服开票";

    public void importOrganizationConfig(List<OrgInitEvent.OrgConfigType> orgConfigEntityList) {
        if(CollectionUtils.isEmpty(orgConfigEntityList)){
            return;
        }

        orgConfigEntityList.forEach(org -> {
            List<MbOrgInfo> mbOrgInfoList = mbOrgInfoLoader.selectByBusinessCode(org.getBusinessCode());
            if (CollectionUtils.isEmpty(mbOrgInfoList)) {
                log.warn("根据businessCode：{}未找到", org.getBusinessCode());
                return;
            }
            OrgConfigInfoVo orgConfigInfo = new OrgConfigInfoVo();
            orgConfigInfo.setProjectIsRequired(TRUE.equals(org.getProjectIsNeed()) ? T : F);
            orgConfigInfo.setCostCenterIsRequired(TRUE.equals(org.getCostCenterIsNeed()) ? T : F);
            orgConfigInfo.setAcrossEnterpriseInvoice(INVOICE_WAY.equals(org.getType()));
            SaveOrgConfigRequest saveOrgConfigRequest = new SaveOrgConfigRequest();
            saveOrgConfigRequest.setOrgConfigInfo(orgConfigInfo);
            saveOrgConfigRequest.setOrgId(mbOrgInfoList.get(0).getOrgId());
            log.warn("保存组织设置:{}", JsonUtils.toJsonString(saveOrgConfigRequest));
            orgConfigService.saveOrgConfig(saveOrgConfigRequest);
        });
    }
}
